const express = require('express');
const multer = require('multer');
const userController = require('../controllers/userController');
const {
  authenticateToken,
  requireSelfOrAdmin,
  requireAdmin
} = require('../middleware/auth');
const {
  validateUserUpdate,
  validateUserId,
  validatePagination,
  validateSearch,
  validateFileUpload,
  handleValidationErrors
} = require('../middleware/validation');

const router = express.Router();

// 配置文件上传中间件
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB
    files: 1
  },
  fileFilter: (req, file, cb) => {
    // 只允许图片文件
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  }
});

/**
 * 用户管理相关路由
 * 基础路径: /api/users
 */

/**
 * @route   GET /api/users/search
 * @desc    搜索用户（管理员功能）
 * @access  Private (Admin only)
 * @headers Authorization: Bearer <token>
 * @query   { keyword?, page?, limit?, sort?, order? }
 */
router.get('/search',
  authenticateToken,
  requireAdmin,
  validateSearch,
  validatePagination,
  handleValidationErrors,
  userController.searchUsers
);

/**
 * @route   GET /api/users/:userId
 * @desc    获取用户信息
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 */
router.get('/:userId',
  authenticateToken,
  validateUserId,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.getUserById
);

/**
 * @route   PUT /api/users/:userId
 * @desc    更新用户信息
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 * @body    { first_name?, last_name?, phone?, date_of_birth?, preferences? }
 */
router.put('/:userId',
  authenticateToken,
  validateUserId,
  validateUserUpdate,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.updateUser
);

/**
 * @route   DELETE /api/users/:userId
 * @desc    删除用户账户（软删除）
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 */
router.delete('/:userId',
  authenticateToken,
  validateUserId,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.deleteUser
);

/**
 * @route   POST /api/users/:userId/avatar
 * @desc    上传用户头像
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 * @body    FormData with 'avatar' file
 */
router.post('/:userId/avatar',
  authenticateToken,
  validateUserId,
  handleValidationErrors,
  requireSelfOrAdmin,
  upload.single('avatar'),
  validateFileUpload,
  handleValidationErrors,
  userController.uploadAvatar
);

/**
 * @route   GET /api/users/:userId/stats
 * @desc    获取用户统计信息
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 */
router.get('/:userId/stats',
  authenticateToken,
  validateUserId,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.getUserStats
);

/**
 * @route   GET /api/users/:userId/orders
 * @desc    获取用户订单历史
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 * @query   { page?, limit?, status? }
 */
router.get('/:userId/orders',
  authenticateToken,
  validateUserId,
  validatePagination,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.getUserOrders
);

/**
 * @route   GET /api/users/:userId/coupons
 * @desc    获取用户优惠券
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 * @query   { status? } // available, used, expired
 */
router.get('/:userId/coupons',
  authenticateToken,
  validateUserId,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.getUserCoupons
);

/**
 * @route   GET /api/users/:userId/points-history
 * @desc    获取用户积分历史
 * @access  Private (Self or Admin)
 * @headers Authorization: Bearer <token>
 * @params  userId
 * @query   { page?, limit? }
 */
router.get('/:userId/points-history',
  authenticateToken,
  validateUserId,
  validatePagination,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.getPointsHistory
);

/**
 * @route   GET /api/users/:userId/loyalty-status
 * @desc    获取用户会员状态
 * @access  Private (Self or Admin)
 */
router.get('/:userId/loyalty-status',
  authenticateToken,
  validateUserId,
  handleValidationErrors,
  requireSelfOrAdmin,
  userController.getLoyaltyStatus
);

// 错误处理中间件（处理multer错误）
router.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        success: false,
        message: '文件大小超过限制（最大5MB）',
        error_code: 'FILE_TOO_LARGE'
      });
    }
    if (error.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({
        success: false,
        message: '文件数量超过限制',
        error_code: 'TOO_MANY_FILES'
      });
    }
    if (error.code === 'LIMIT_UNEXPECTED_FILE') {
      return res.status(400).json({
        success: false,
        message: '意外的文件字段',
        error_code: 'UNEXPECTED_FILE'
      });
    }
  }
  
  if (error.message === '只允许上传图片文件') {
    return res.status(400).json({
      success: false,
      message: '只允许上传图片文件',
      error_code: 'INVALID_FILE_TYPE'
    });
  }
  
  next(error);
});

module.exports = router;